package cn.leyaber.hrm.detalis;




import cn.leyaber.hrm.clients.UserFeignClient;
import cn.leyaber.hrm.domain.Login;
import cn.leyaber.hrm.mapper.LoginMapper;

import cn.leyaber.hrm.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private LoginMapper loginMapper;
    @Resource
    private UserFeignClient userFeignClient;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户
        Login login = loginMapper.selectByUsername(username);
        if(login == null){
            throw new UsernameNotFoundException("这是一个无效的用户");
        }
        //查询权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
          /*
            判断是不是后台用户如果是就需要加载权限
            */

        if(login.getType() == Login.TYPE_SYSTEM){
            //查询用户的权限
            AjaxResult ajaxResult = userFeignClient.getByLoginId(login.getId());
            if(!ajaxResult.isSuccess() || ajaxResult.getResultObj() == null){
                throw new AuthenticationServiceException("加载失败权限");
            }
            //获取权限的列表
            List<String> permissions =  (List<String>)ajaxResult.getResultObj();
            /*
              转换权限
            */
            permissions.forEach( permissionSn -> {
                authorities.add(new SimpleGrantedAuthority(permissionSn));
            });
        }
        /*
         返回userDetails
         */
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                username,login.getPassword(),authorities);
        return userDetails;
    }
}
